<template>
  <a-card :bordered="false" v-show="visible" class="card" :title="modalTitle">
    <a-form :form="form">
      <a-form-item v-show="false" >
        <a-input v-decorator="['id']" type="hidden"/>
        <a-input v-decorator="['storeId']" type="hidden"/>
        <a-input v-decorator="['pickId']" type="hidden"/>
      </a-form-item>
      <a-row :gutter="24">
        <!-- <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="出库单号"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              disabled
              v-decorator="['outNo', {rules: [{required: false, message: '出库单号不能为空'}]}]" />
          </a-form-item>
        </a-col> -->
        <!--        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="领用/退货单号"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              disabled
              style="width: 70%"
              v-decorator="['pickNo']"/>
            <a-button type="primary" style="width: 30%" @click="handleSparePickFormSelect">选择</a-button>
          </a-form-item>
        </a-col>
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="仓库"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-tree-select
              style="width: 100%"
              @change="handleStoreChange"
              :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
              :treeData="storeTreeDate"
              :treeNodeFilterProp="'title'"
              :showSearch="true"
              v-decorator="['storeId', {rules: [{required: false, message: '仓库不能为空'}]}]"
              placeholder="请选择"
            >
            </a-tree-select>
          </a-form-item>
        </a-col>-->
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="出库类型"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select @change="typeChange" v-decorator="['type', {initValue: 1, rules: [{required: true, message: '出库类型不能为空'}]}]" placeholder="请选择">
              <a-select-option
                v-for="(label,value) in typeMap"
                :key="value"
                :label="label"
                :value="parseInt(value)">{{ label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <!--        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="操作人"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select v-decorator="['userId']" placeholder="请选择">
              <a-select-option
                v-for="({userId, realName}) in userList"
                :key="userId"
                :label="realName"
                :value="userId">{{ realName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>-->
        <!-- <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="操作时间"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-date-picker
              style="width: 100%"
              :format="BaseTool.Date.PICKER_NORM_DATE_PATTERN"
              v-decorator="['userTime', {rules: [{required: true, message: '操作时间不能为空'}]}]" />
          </a-form-item>
        </a-col> -->
        <a-col :lg="12" :md="24" :sm="24">
          <a-form-item
            label="备注"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-textarea
              :rows="4"
              v-decorator="['remark', {rules: [{required: false, message: '备注不能为空'}]}]"/>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <title-divider title="备件明细" width="90px"></title-divider>
    <div class="table-operator">
      <a-button size="small" type="primary" @click="handleSpareStoreSelect">
        <a-icon type="plus"/>
        添加
      </a-button>
      <a-button class="margin-left8" size="small" type="danger" @click="handleDel">
        <a-icon type="delete"/>
        删除
      </a-button>
    </div>
    <a-table
      bordered
      :data-source="data"
      :columns="columns"
      tableLayout="auto"
      rowKey="id"
      :row-selection="rowSelection">
      <template slot="num" slot-scope="text, record">
        <div class="editable-cell-input-wrapper">
          <a-input :value="text" :id="record.spareId + ',num'" @change="$event => onQuantityChange($event, record.id, 'num')" />
        </div>
      </template>
      <template slot="totalPrice" slot-scope="text, record">
        <div class="editable-cell-input-wrapper">
          <a-input :value="text" :id="record.spareId + ',totalPrice'" @change="$event => onTotalPriceChange($event, record.id, 'totalPrice')" />
        </div>
      </template>
      <span slot="action" slot-scope="record">
        <template>
          <a @click="handleBaseFormForModifySelect(record)">修改</a>
          <a-divider type="vertical" />
          <a-popconfirm title="是否要删除该条数据？" @confirm="handleDelOne(record.id)">
            <a>删除</a>
          </a-popconfirm>
        </template>
      </span>
    </a-table>
    <a-row :gutter="48" >
      <a-col :md="48" :sm="48">
        <span class="table-page-search-submitButtons" style="float: right;margin-top: 10px">
          <a-button type="primary" @click="save()">提交</a-button>
          <a-button style="margin-left: 8px" @click="handleCancel()">返回</a-button>
        </span>
      </a-col>
    </a-row>
    <spare-pick-form-select-modal ref="sparePickFormSelectModal" @selected="handleSparePickFormSelected"/>
    <spare-back-form-select-modal ref="spareBackFormSelectModal" @selected="handleSpareBackFormSelected"/>
    <spare-store-select-modal ref="spareStoreSelectModal" @selected="handleSpareStoreSelected"/>
    <detail-base-form ref="detailBaseForm" @selected="handleDetailSelected"/>
    <store-select-modal ref="storeSelectModal" @selected="handleStoreSelected"/>
    <base-form-for-modify ref="baseFormForModify" @selected="handleBaseFormForModifySelected"/>
  </a-card>
</template>

<script>
import pick from 'lodash.pick'
import { addOutStoreForm, updateOutStoreForm } from '@/api/store/outstoreform'
import SparePickFormSelectModal from '@/views/store/sparepickform/modules/SparePickFormSelectModal'
import SpareBackFormSelectModal from '@/views/store/sparebackform/modules/SpareBackFormSelectModal'
import DetailBaseForm from './DetailBaseForm'
import StoreSelectModal from '@/views/store/store/modules/StoreSelectModal'
import SpareStoreSelectModal from '@/views/store/sparestore/modules/SpareStoreSelectModal'
import BaseFormForModify from '@/views/store/outstoredetail/modules/BaseFormForModify'
import BaseTool from '@/utils/tool'
import { queryUsersByParentDeptNatureAll } from '@/api/upms/user'
import { fetchStoreTree } from '@/api/store/store'

export default {
  name: 'BaseOutStoreForm',
  components: {
    DetailBaseForm,
    SparePickFormSelectModal,
    SpareBackFormSelectModal,
    SpareStoreSelectModal,
    StoreSelectModal,
    BaseFormForModify
  },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      maskClosable: false,
      type: 1,
      storeId: null,
      // 下拉框map
      typeMap: {},
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          customRender: (text, record, index) => {
            return index + 1
          }
        },
        {
          title: '名称',
          dataIndex: 'spareId',
          customRender: (text, record, index) => {
            return record.spareName
          }
        },
        {
          title: '编号',
          dataIndex: 'no'
        },
        {
          title: '规格',
          dataIndex: 'ggxh'
        },
        {
          title: '原厂编号',
          dataIndex: 'initNo'
        },
        {
          title: '数量',
          dataIndex: 'num',
          width: 150,
          scopedSlots: { customRender: 'num' }
        },
        {
          title: '价格',
          dataIndex: 'price',
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '总价',
          dataIndex: 'totalPrice',
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '所在仓库',
          dataIndex: 'storeName'
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      data: [],
      storeTreeDate: [],
      userList: {},
      user: this.$store.getters.userInfo,
      selectedRowKeys: [],
      selectedRows: [],
      options: {
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys
        }
      },
      rowSelection: {
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
        }
      }
    }
  },
  props: {
  },
  created () {
    // 下拉框map
    this.typeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.OUT_STORE_FORM_TYPE)
  },
  methods: {
    base (record) {
      this.visible = true
      const params = { deptId: this.user.companyId }
      params.nature = this.DictCache.VALUE.SYS_DEPT_NATURE.FEN_GONG_SI
      queryUsersByParentDeptNatureAll(params).then(res => {
        this.userList = res.data
      })
      fetchStoreTree().then(res => {
        this.storeTreeDate = res.data
      })
      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.modalTitle = '添加'
        this.data = []
        return
      }
      this.modalTitle = '编辑'
      const { form: { setFieldsValue } } = this
      // 日期处理
      this.storeId = record.storeId
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'outNo',
          'userId',
          'userTime',
          'storeId',
          'storeName',
          'pickId',
          'pickNo',
          'type',
          'remark'
        ])))
      })
      this.data = record.detailList
    },
    save () {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        if (this.data.length === 0) {
          this.$message.error('请添加出库详情')
          this.confirmLoading = false
          return
        }
        values.detailList = this.data
        values.userTime = BaseTool.Date.formatter(values.userTime, BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        // 日期处理
        if (this.BaseTool.String.isBlank(values.id)) {
          addOutStoreForm(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updateOutStoreForm(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },

    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      if (this.BaseTool.Object.isNotBlank(values)) {
        this.$emit('ok', values)
      } else {
        this.$emit('ok')
      }
    },
    typeChange (values) {
      this.type = values
    },
    handleStoreSelect () {
      this.$refs.storeSelectModal.base({}, { filter: -1 })
    },
    handleStoreSelected (record, keys, rows) {
      // 重新选择了仓库，则明细需要全部清空
      this.data = []
      const [ key ] = keys
      const [ row ] = rows
      const { form: { setFieldsValue } } = this
      this.storeId = key
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign({
          'storeId': key,
          'storeName': row.name
        }))
      })
    },
    handleSparePickFormSelect () {
      if (this.type === 1) {
        this.$refs.sparePickFormSelectModal.base()
      } else {
        this.$refs.spareBackFormSelectModal.base()
      }
    },
    handleSparePickFormSelected (record, keys, rows) {
      const [ key ] = keys
      const [ row ] = rows
      const { form: { setFieldsValue } } = this
      // 日期处理
      setFieldsValue(Object.assign({
        'pickId': key,
        'pickNo': row.pickNo
      }))
    },
    handleSpareBackFormSelected (record, keys, rows) {
      const [ key ] = keys
      const [ row ] = rows
      const { form: { setFieldsValue } } = this
      // 日期处理
      setFieldsValue(Object.assign({
        'pickId': key,
        'pickNo': row.pickNo
      }))
    },
    handleDetailSelect () {
      if (this.storeId == null) {
        this.$message.error('请先选择仓库')
        return
      }
      this.$refs.detailBaseForm.base({ storeId: this.storeId })
    },
    handleDetailSelected (record) {
      const { data } = this
      data.push(record)
    },
    handleDel (id) {
      const data = [...this.data]
      if (this.selectedRowKeys.length === 0) {
        this.$message.error('请至少选择一条数据')
        return
      }
      this.data = data.filter(item => !this.selectedRowKeys.includes(item.id))
    },
    handleDelOne (id) {
      const data = [...this.data]
      this.data = data.filter(item => id !== item.id)
    },
    handleSpareStoreSelect () {
      this.$refs.spareStoreSelectModal.base({}, { num: 0 })
    },
    handleSpareStoreSelected (record, keys, rows) {
      const { data } = this
      for (let i = 0; i < rows.length; i++) {
        var find = false
        for (let j = 0; j < data.length; j++) {
          if (rows[i].id === data[j].id || rows[i].spareId === data[j].spareId) {
            find = true
            break
          }
        }
        if (!find) {
          const selectData = rows[i]
          selectData.num = 1
          selectData.totalPrice = selectData.price
          selectData.storeId = rows[i].storeId
          selectData.storeName = rows[i].storeName
          data.push(selectData)
        }
      }
    },
    handleStoreChange (value) {
      this.storeId = value
    },
    handleBaseFormForModifySelect (record) {
      this.$refs.baseFormForModify.base(record)
    },
    handleBaseFormForModifySelected (values) {
      console.log('values' + values.id)
      const { data } = this
      for (let j = 0; j < data.length; j++) {
        if (values.id === data[j].id) {
          data[j].num = values.num
          data[j].totalPrice = values.totalPrice
          break
        }
      }
    },
    onQuantityChange (e, id, attr) {
      const value = e.target.value
      console.log(value)
      if (value !== 0 && !value) {
        return
      }
      const data = [...this.data]
      const target = data.find(item => item.id === id)
      console.log('target: ' + target)
      if (target) {
        target[attr] = value
        target['totalPrice'] = Math.floor(value * target['price'] * 10000) / 10000
        this.data = data
      }
    },
    onTotalPriceChange (e, id, attr) {
      const value = e.target.value
      console.log(value)
      if (value !== 0 && !value) {
        return
      }
      const data = [...this.data]
      const target = data.find(item => item.id === id)
      console.log('target: ' + target)
      if (target) {
        target[attr] = value
        this.data = data
      }
    }
  }
}
</script>
